package librus.codebase.packers;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;

import librus.codebase.util.FileUtil;

import de.innosystec.unrar.Archive;
import de.innosystec.unrar.exception.RarException;
import de.innosystec.unrar.rarfile.FileHeader;


public class Unrar implements IPacker
{
	private Archive __archive;
	
	private Map<String,FileHeader> __fileMap;
	
	public LinkedList<String> getFiles(String path) throws RarException, IOException
	{
		LinkedList<String> result = new LinkedList<String>();
		
		File file = new File(path);
		
		if (!file.exists())			
			throw new FileNotFoundException("File not found");
		
		Archive arc = new Archive(file);
			
		List<FileHeader> files = arc.getFileHeaders();
		
		for (int i=0; i<files.size(); i++)
		{
			FileHeader header = files.get(i);
			String name = header.getFileNameString();
			if (FileUtil.isComicFile(name))
				result.add(name);
		}
		
		return result;
	}
	
	public Boolean openArchive(String archivePath)
	{
		Boolean result = false;
		try {
			File file = new File(archivePath);
			
			if (!file.exists())			
				throw new FileNotFoundException("File not found");
			
			__archive =  new Archive(file);		
			__fileMap = new HashMap<String, FileHeader>();

			List<FileHeader> files = __archive.getFileHeaders();	
			FileHeader header;
			for (int i=0; i<files.size(); i++)
			{
				 header = files.get(i);
				__fileMap.put(header.getFileNameString(), header);
			}			
			
			result = true;			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	public Boolean closeArchive()
	{
		Boolean result = false;
		try 
		{			
			__archive.close();
			__fileMap.clear();
			
			__archive = null;
			__fileMap = null;
			
			result = true;			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	} 
	
	public BufferedImage getImage(String imageName)
	{
		BufferedImage image = null;
		
		try 
		{				
			FileHeader header = __fileMap.get(imageName);
			ByteArrayOutputStream output = new ByteArrayOutputStream();
			
			__archive.extractFile(header, output);			

			InputStream input = new ByteArrayInputStream(output.toByteArray());
			image = ImageIO.read(input);
		} 
		catch (Exception ioe) {
			ioe.printStackTrace();
		}
		
		return image;
	}
	
}
